package com.bsoft.service.impl;

import com.bsoft.Exception.CommonException;
import com.bsoft.controller.JSON.ThirdLevelPubHosPerformanceAssessController;
import com.bsoft.mapper.business.ThirdLevelPubHosPerformanceAssessMapper;
import com.bsoft.service.ThirdLevelPubHosPerformanceAssessService;
import com.bsoft.utils.ConmonUtil;
import com.bsoft.utils.VcsGeneratorUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ThirdLevelPubHosPerformanceAssessServiceImpl extends ConmonUtil implements ThirdLevelPubHosPerformanceAssessService {
    private static Logger logger = LoggerFactory.getLogger(ThirdLevelPubHosPerformanceAssessServiceImpl.class);

    @Autowired
    ThirdLevelPubHosPerformanceAssessMapper thirdLevelPubHosMapper;

    public  static final String path = "D:/VcsFile/";
    public  static final String hosCode = "CZZYY";
    public  static final String hosName = "平昌中医院";

    /**
     * 住院医嘱数据采集:医院住院医嘱数据上传 hosInpatientOrderUplod
     */
    @Override
    public String hosInpatientOrderUplod(Map<String, Object> req) throws Exception{
        isNUll(req,Arrays.asList("beginTime","endTime","idOrg","viewName","dicName"));
        String[] timeArr = req.get("beginTime").toString().split("-");
        String  yearMonth = timeArr[0];

        pagination(req);
        List<LinkedHashMap<String, Object>> hosOrderList = thirdLevelPubHosMapper.queryHosInpatientOrder(req);
        /*int batchSize = 9000;
        List<List<Map<String, Object>>> partitionList = Lists.partition(hosOrderList, batchSize);

        for (int i = 0; i < partitionList.size(); i++) {
            VcsGeneratorUtil.generateVcsZip(hosName,hosCode,i+1,partitionList.get(i), req.get("dicName").toString(), (path+"HosOrderZip/"),yearMonth);
            logger.info("住院医嘱数据采集:当前循环次数{}:当次生成vcs文件的医嘱数量数量: {}", i ,partitionList.get(i).size());
        }*/

        // 遍历每个Map，移除ROW_ID（注意键的大小写，数据库通常返回大写）
        hosOrderList.forEach(map -> {
            map.remove("ROW_ID"); // 若实际键是小写row_id，改为map.remove("row_id")
        });

        PageInfo<LinkedHashMap<String, Object>> pageInfo = new PageInfo<LinkedHashMap<String, Object>>(hosOrderList);
        JSONArray jsonArray = JSONArray.fromObject(pageInfo.getList());
        JSONObject json = new JSONObject();
        json.put("total", pageInfo.getTotal());
        json.put("data", jsonArray);
        json.put("code", "200");
        json.put("msg", "请求成功");
        return json.toString();
    }


    /**
     * 门诊数据采集:中医门（急）诊诊疗信息上传说明
     */
    @Override
    public String hosOutpatientOrderUplod(Map<String, Object> req) throws Exception{
        isNUll(req,Arrays.asList("beginTime","endTime","idOrg","viewName","dicName"));
        String[] timeArr = req.get("beginTime").toString().split("-");
        String  yearMonth = timeArr[0]+timeArr[1];
        pagination(req);
        List<LinkedHashMap<String, Object>> hosOrderList = null;
        //List<LinkedHashMap<String, Object>> hosOrderList = thirdLevelPubHosMapper.queryHosOutpatinetOrder(req);
        /*int batchSize = 49000;
        List<List<Map<String, Object>>> partitionList = Lists.partition(hosOrderList, batchSize);

        for (int i = 0; i < partitionList.size(); i++) {
            VcsGeneratorUtil.generateVcsZip(hosName,hosCode,i+1,partitionList.get(i), req.get("dicName").toString(), (path+"HosOrderZip/"),yearMonth);
            logger.info("门诊数据采集:当前循环次数{}:当次生成vcs文件的医嘱数量数量: {}", i ,partitionList.get(i).size());
        }*/
        PageInfo<LinkedHashMap<String, Object>> pageInfo = new PageInfo<LinkedHashMap<String, Object>>(hosOrderList);
        JSONArray jsonArray = JSONArray.fromObject(pageInfo.getList());
        JSONObject json = new JSONObject();
        json.put("total", pageInfo.getTotal());
        json.put("data", jsonArray);
        json.put("code", "200");
        json.put("msg", "请求成功");
        return json.toString();
    }


    /**视图
     * dicName 医院剂型字典数据上传 dicType=1 HosDosageFormDicUplod
     * dicName 医院给药途径字典数据上传 dicType=2 hosAdministraWayDicUplod
     * dicName 中医类操作字典数据上传 dicType=3  herbalistOperateDicUplod
     */
    @Override
    public String thirdLevelPubHosDicUplod(Map<String, Object> req) throws Exception {
        isNUll(req, Arrays.asList("dicName", "viewName", "idOrg"));

        pagination(req);
        List<Map<String, Object>> list = thirdLevelPubHosMapper.queryThirdLevelPubHosDic(req);
        if (CollectionUtils.isEmpty(list)) throw new CommonException("获取到字典[" + req.get("viewName") + "]数据为空!");
        // 生成VCS文件 "D:/VcsFile/"+
        String  fileName = "PCXZYY" + "_" + req.get("dicName") + ".vcs";
        //VcsGeneratorUtil.generateVcs(list, fileName);

        logger.info("[" + req.get("viewName") + "]VCS文件生成成功!");
        logger.info("文件路径：" + System.getProperty("user.dir") + "D:/VcsFile/calendar_events.vcs");
        return getSuccessPagination(list);
    }
}
